package com.esunrise.shop.common.config;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.RequestFacade;
import org.apache.catalina.connector.ResponseFacade;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.lang.reflect.Field;
//代理测试环境data

@WebFilter(urlPatterns = "/data/*",filterName = "redirctFilter")
public class RedirectFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        boolean done = false;
        if(servletRequest instanceof RequestFacade){
            RequestFacade facade = (RequestFacade) servletRequest;
            Request request = getRequest(facade);
            if(request!=null){
                String requestURI = request.getRequestURI();
                if(requestURI.startsWith("/data/")){
                    ResponseFacade resp = (ResponseFacade) servletResponse;
                    resp.sendRedirect("https://qashop.esunrise.net" + requestURI);
                    resp.flushBuffer();
                    resp.finish();
                    return;
                }
            }
        }
        if(!done){
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

    private static Request getRequest(RequestFacade facade){
        try{
            Field f = RequestFacade.class.getDeclaredField("request");
            f.setAccessible(true);
            Request r = (Request)f.get(facade);
            return r;
        }catch (Exception e){
            return null;
        }

    }
}
